/**
 * MIT License
 *
 * Copyright (c) 2024 小村程序员
 * Email: 397237738@qq.com
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.open.cobertura.core.instrument;

import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.open.cobertura.core.util.CoberturaLabelStatefulUtil;

/**
 * Label有状态标签的访问器
 */
public class CoberturaLabelStatefulVisitor extends MethodVisitor {

    /**
     * 是否是第一条指令
     */
    private boolean isFast=true;
    /**
     * 是否存在潜在的下一条指令
     */
    private boolean isNext=false;
    /**
     * 是否存在潜在的上一条指令
     */
    private boolean isPrevious=false;

    /**
     * 设置行号
     */
    private int lineNumber=0;

    /**
     * 方法的开始行，一般方法的开始行是不插入探针的
     */
    private Label methodBeginLine;
    public CoberturaLabelStatefulVisitor() {
        super(Opcodes.ASM9);
    }


    @Override
    public void visitJumpInsn(int opcode, Label label) {
        CoberturaLabelStatefulUtil.setLabelStateForIsJump(label,this.lineNumber);
        if (opcode == Opcodes.JSR) {
            throw new AssertionError("Subroutines not supported.");
        }
        //如果是goto指令，表示前后两条指令是断开的
        if(opcode==Opcodes.GOTO) {
            isNext = false;
        }else{
            isNext = true;
        }
        isFast = false;
    }

    @Override
    public void visitInsn(final int opcode) {
        switch (opcode) {
            case Opcodes.RET:
                throw new AssertionError("Subroutines not supported.");
            case Opcodes.IRETURN:
            case Opcodes.LRETURN:
            case Opcodes.FRETURN:
            case Opcodes.DRETURN:
            case Opcodes.ARETURN:
            case Opcodes.RETURN:
            case Opcodes.ATHROW:
                isNext = false;
                break;
            default:
                isNext = true;
                break;
        }
        isFast = false;
    }

    @Override
    public void visitTableSwitchInsn(final int min, final int max,
                                     final Label dflt, final Label... labels) {
        visitSwitchInsn(dflt, labels);
    }

    @Override
    public void visitLookupSwitchInsn(final Label dflt, final int[] keys,
                                      final Label[] labels) {
        visitSwitchInsn(dflt, labels);
    }

    private void visitSwitchInsn(final Label dflt, final Label[] labels) {

        isNext = false;
        isFast = false;
    }

    @Override
    public void visitLabel(Label label) {
        if(isFast){
            CoberturaLabelStatefulUtil.setLabelStateForIsJump(label,this.lineNumber);
        }
        if(isNext){
            CoberturaLabelStatefulUtil.setLabelStateForIsMultiJump(label,this.lineNumber);
        }
    }

    @Override
    public void visitLineNumber(int line, Label start) {
        this.methodBeginLine=start;
        this.lineNumber=line;
    }

    @Override
    public void visitIntInsn(final int opcode, final int operand) {
        isNext = true;
        isFast = false;
    }

    @Override
    public void visitVarInsn(final int opcode, final int var) {
        isNext = true;
        isFast = false;
    }

    @Override
    public void visitTypeInsn(final int opcode, final String type) {
        isNext = true;
        isFast = false;
    }

    @Override
    public void visitFieldInsn(final int opcode, final String owner,
                               final String name, final String desc) {
        isNext = true;
        isFast = false;
    }

    @Override
    public void visitMethodInsn(final int opcode, final String owner,
                                final String name, final String desc, final boolean itf) {
        isNext = true;
        isFast = false;
        markMethodBeginLine();
    }

    @Override
    public void visitInvokeDynamicInsn(final String name, final String desc,
                                       final Handle bsm, final Object... bsmArgs) {
        isNext = true;
        isFast = false;
        markMethodBeginLine();
    }

    /**
     * 标记是否为方法的开始行
     */
    private void markMethodBeginLine() {
        if (methodBeginLine != null) {
            CoberturaLabelStatefulUtil.setMethodBeginLine(methodBeginLine,this.lineNumber);
        }
    }

    @Override
    public void visitLdcInsn(final Object cst) {
        isNext = true;
        isFast = false;
    }

    @Override
    public void visitIincInsn(final int var, final int increment) {
        isNext = true;
        isFast = false;
    }

    @Override
    public void visitMultiANewArrayInsn(final String desc, final int dims) {
        isNext = true;
        isFast = false;
    }
}
